<template>
  <div class="apple-style-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">主机出租</h1>
    </div>

    <!-- 查询条件区域 -->
    <el-card class="filter-card apple-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
        <el-form-item label="客户名称">
          <el-input v-model="queryParams.customer_name" placeholder="请输入客户名称" clearable class="apple-input" />
        </el-form-item>
        <el-form-item label="订单号">
          <el-input v-model="queryParams.order_number" placeholder="请输入订单号" clearable class="apple-input" />
        </el-form-item>
        <el-form-item label="域名">
          <el-input v-model="queryParams.domain_name" placeholder="请输入域名" clearable class="apple-input" />
        </el-form-item>
        <el-form-item label="对接人">
          <el-input v-model="queryParams.nickname" placeholder="请输入对接人" clearable class="apple-input" />
        </el-form-item>
        <el-form-item label="下单日期">
          <el-date-picker
            v-model="dateRange.order_date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            class="apple-date-picker"
          />
        </el-form-item>
        <el-form-item label="截至日期">
          <el-date-picker
            v-model="dateRange.expiry_date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            class="apple-date-picker"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" class="apple-button primary-button">点击查询</el-button>
          <el-button @click="resetQuery" class="apple-button">重置查询条件</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表区域 -->
    <el-card class="table-card apple-card">
      <div class="table-header">
        <div class="left-buttons">
          <el-button type="primary" @click="handleAdd" class="apple-button primary-button">
            <el-icon><Plus /></el-icon> 添加
          </el-button>
          <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete" class="apple-button danger-button">
            <el-icon><Delete /></el-icon> 删除
          </el-button>
        </div>
        <div class="right-buttons">
          <el-button type="success" @click="handleExport" :loading="exportLoading" class="apple-button success-button">
            <el-icon><Download /></el-icon> {{ isFiltered ? '导出筛选数据' : '导出全部数据' }}
          </el-button>
          <el-button type="primary" @click="handleImport" class="apple-button primary-button">
            <el-icon><Upload /></el-icon> 导入
          </el-button>
        </div>
      </div>
      
      <el-table
        v-loading="loading"
        :data="rentalList"
        @selection-change="handleSelectionChange"
        border
        style="width: 100%"
        class="apple-table"
      >
        <el-table-column type="selection" width="45" />
        <el-table-column label="操作" width="150" fixed="left">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)" class="apple-link-button">编辑</el-button>
            <el-button type="primary" link @click="handleView(scope.row)" class="apple-link-button">查看</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)" class="apple-link-button">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="order_number" label="订单号" min-width="130" />
        <el-table-column prop="customer_display" label="客户名称" min-width="120" />
        <el-table-column prop="order_amount" label="订单金额" min-width="90" sortable />
        <el-table-column prop="rental_years" label="出租年限" min-width="90" sortable />
        <el-table-column prop="domain_name" label="网站域名" min-width="140" />
        <el-table-column prop="effective_date" label="生效日期" min-width="100" sortable>
          <template #default="scope">
            {{ formatDate(scope.row.effective_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="expiry_date" label="截至日期" min-width="100" sortable>
          <template #default="scope">
            {{ formatDate(scope.row.expiry_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="nickname_display" label="对接人" min-width="90" />
        <el-table-column prop="order_remarks" label="订单备注" min-width="140" show-overflow-tooltip />
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="apple-pagination"
        />
      </div>
    </el-card>

    <!-- 添加/编辑订单弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="850px"
      append-to-body
      destroy-on-close
      class="apple-dialog"
    >
      <el-form
        ref="rentalFormRef"
        :model="rentalForm"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="下单客户" prop="customer">
              <div class="customer-select-wrapper">
                <el-select
                  v-model="rentalForm.customer"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入客户名称"
                  :remote-method="remoteCustomerSearch"
                  :loading="customerLoading"
                  style="width: 100%"
                  @change="handleCustomerSelectChange"
                  class="apple-select"
                >
                  <el-option
                    v-for="item in customerOptions"
                    :key="item.id"
                    :label="item.customer_name"
                    :value="item.id"
                  />
                  <el-option
                    v-if="searchCustomerKeyword && showCreateOption"
                    :value="'create_new'"
                    :label="`创建新客户: ${searchCustomerKeyword}`"
                  />
                </el-select>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单号" prop="order_number">
              <el-input v-model="rentalForm.order_number" placeholder="请输入订单号" class="apple-input" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出租年限" prop="rental_years">
              <el-select v-model="rentalForm.rental_years" placeholder="请选择年限" style="width: 100%" class="apple-select">
                <el-option :value="0" label="永久" />
                <el-option :value="1" label="1年" />
                <el-option :value="2" label="2年" />
                <el-option :value="3" label="3年" />
                <el-option :value="4" label="4年" />
                <el-option :value="5" label="5年" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单金额" prop="order_amount">
              <el-input v-model="rentalForm.order_amount" placeholder="请输入金额" class="apple-input">
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单来源" prop="order_source">
              <el-select v-model="rentalForm.order_source" placeholder="请选择来源" style="width: 100%" class="apple-select">
                <el-option :value="0" label="Newbe工作室" />
                <el-option :value="1" label="纽币德信息科技" />
                <el-option :value="2" label="官方网站" />
                <el-option :value="3" label="其它" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="对接人" prop="nickname">
              <el-select 
                v-model="rentalForm.nickname" 
                placeholder="请输入或选择对接人" 
                style="width: 100%" 
                class="apple-select"
                filterable
                remote
                reserve-keyword
                :remote-method="remoteUserSearch"
                :loading="userLoading"
                @change="handleUserSelectChange"
                default-first-option
              >
                <el-option
                  v-for="item in userOptions"
                  :key="item.id"
                  :label="item.nickname"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="网站域名" prop="domain_name">
          <el-input v-model="rentalForm.domain_name" placeholder="请输入域名或IP地址" class="apple-input" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生效日期" prop="effective_date">
              <el-date-picker v-model="rentalForm.effective_date" type="date" placeholder="选择日期" style="width: 100%" value-format="YYYY-MM-DD" class="apple-date-picker" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截至日期" prop="expiry_date">
              <el-date-picker v-model="rentalForm.expiry_date" type="date" placeholder="选择日期" style="width: 100%" value-format="YYYY-MM-DD" class="apple-date-picker" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="rentalForm.email" placeholder="请输入电子邮箱" class="apple-input" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="mobile">
              <el-input v-model="rentalForm.mobile" placeholder="请输入手机号码" class="apple-input" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="客户微信" prop="customer_wechat">
          <el-input v-model="rentalForm.customer_wechat" placeholder="请输入客户微信" class="apple-input" />
        </el-form-item>

        <el-form-item label="订单备注" prop="order_remarks">
          <el-input v-model="rentalForm.order_remarks" type="textarea" :rows="3" placeholder="请输入备注信息" class="apple-textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" class="apple-button">取消</el-button>
          <el-button type="primary" @click="submitForm" class="apple-button primary-button">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看订单详情弹窗 -->
    <el-dialog
      title="主机出租订单详情"
      v-model="viewDialogVisible"
      width="1000px"
      append-to-body
      destroy-on-close
      class="apple-dialog rental-detail-dialog"
    >
      <div v-if="Object.keys(detailData).length === 0" class="empty-data">
        <el-empty description="暂无详情数据" />
      </div>
      <div v-else class="rental-detail-container">
        <!-- 头部区域 -->
        <div class="detail-header">
          <div class="detail-title">
            <h2>订单号: {{ detailData.order_number }}</h2>
            <el-tag size="small" effect="plain" type="primary" class="domain-tag">{{ detailData.domain_name }}</el-tag>
          </div>
          <div class="detail-amount">¥ {{ detailData.order_amount }}</div>
        </div>
        
        <!-- 内容区域 - 水平布局 -->
        <div class="detail-content">
          <div class="detail-columns">
            <!-- 左侧列 -->
            <div class="detail-column">
              <div class="detail-section">
                <h3 class="section-title">基本信息</h3>
                <div class="detail-grid">
                  <div class="detail-item">
                    <div class="item-label">客户名称</div>
                    <div class="item-value">{{ detailData.customer_display || (detailData.customer && detailData.customer.customer_name) }}</div>
                  </div>
                  <div class="detail-item">
                    <div class="item-label">出租年限</div>
                    <div class="item-value">{{ detailData.rental_years }} 年</div>
                  </div>
                  <div class="detail-item">
                    <div class="item-label">订单来源</div>
                    <div class="item-value">{{ detailData.order_source_display || getOrderSourceName(detailData.order_source) }}</div>
                  </div>
                  <div class="detail-item">
                    <div class="item-label">对接人</div>
                    <div class="item-value">{{ detailData.nickname_display || (detailData.nickname && detailData.nickname.nickname) }}</div>
                  </div>
                </div>
              </div>
              
              <div class="detail-section">
                <h3 class="section-title">日期信息</h3>
                <div class="detail-grid">
                  <div class="detail-item">
                    <div class="item-label">生效日期</div>
                    <div class="item-value">{{ formatDate(detailData.effective_date) }}</div>
                  </div>
                  <div class="detail-item">
                    <div class="item-label">截至日期</div>
                    <div class="item-value">{{ formatDate(detailData.expiry_date) }}</div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 右侧列 -->
            <div class="detail-column">
              <div class="detail-section">
                <h3 class="section-title">联系方式</h3>
                <div class="detail-grid">
                  <div class="detail-item">
                    <div class="item-label">电子邮箱</div>
                    <div class="item-value">{{ detailData.email || '无' }}</div>
                  </div>
                  <div class="detail-item">
                    <div class="item-label">手机号码</div>
                    <div class="item-value">{{ detailData.mobile || '无' }}</div>
                  </div>
                  <div class="detail-item">
                    <div class="item-label">客户微信</div>
                    <div class="item-value">{{ detailData.customer_wechat || '无' }}</div>
                  </div>
                </div>
              </div>
              
              <div class="detail-section">
                <h3 class="section-title">系统信息</h3>
                <div class="detail-grid">
                  <div class="detail-item">
                    <div class="item-label">创建日期</div>
                    <div class="item-value">{{ formatDate(detailData.creation_date) }}</div>
                  </div>
                  <div class="detail-item">
                    <div class="item-label">最后修改日期</div>
                    <div class="item-value">{{ formatDate(detailData.last_modification_date) }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 备注区域 - 横跨整个宽度 -->
          <div class="detail-section full-width">
            <h3 class="section-title">订单备注</h3>
            <div class="remarks-box">
              <p v-if="detailData.order_remarks">{{ detailData.order_remarks }}</p>
              <p v-else class="no-data">暂无备注</p>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewDialogVisible = false" class="apple-button close-button">关闭</el-button>
          <el-button type="primary" @click="handleEdit(detailData)" class="apple-button edit-button">编辑订单</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加导入弹窗 -->
    <el-dialog
      title="导入主机出租数据"
      v-model="importDialogVisible"
      width="500px"
      append-to-body
      destroy-on-close
      class="apple-dialog"
    >
      <div class="import-dialog-content">
        <p class="import-tip">请上传Excel文件(.xlsx格式)</p>
        <el-upload
          class="upload-demo"
          action="#"
          :auto-upload="false"
          :on-change="handleFileChange"
          :file-list="fileList"
          :limit="1"
          accept=".xlsx"
        >
          <template #trigger>
            <el-button type="primary" class="apple-button primary-button">选择文件</el-button>
          </template>
          <template #tip>
            <div class="el-upload__tip">
              <p>请确保Excel表头包含：订单号、客户名称、订单金额、出租年限、域名、生效日期、截至日期等字段</p>
              <p>
                <el-button type="text" @click="downloadTemplate" class="download-template-btn">
                  <el-icon><Download /></el-icon> 下载导入模板
                </el-button>
              </p>
            </div>
          </template>
        </el-upload>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false" class="apple-button">取消</el-button>
          <el-button type="primary" @click="submitImport" :loading="importLoading" :disabled="!selectedFile" class="apple-button primary-button">
            导入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Delete, Download, Upload } from '@element-plus/icons-vue';
import { 
  getHostOrderList as getRentalList, 
  getHostOrder as getRental,
  createHostOrder as createRental,
  updateHostOrder as updateRental,
  deleteHostOrder as deleteRental,
  batchDeleteHostOrders as batchDeleteRentals,
  exportHostOrders as exportRentals,
  importRentals,
  getHostOrderImportTemplate
} from '@/api/host-order';
import { getCustomerList, createCustomer } from '@/api/customers';
import { getUserList } from '@/api/users';

// 查询参数
const queryParams = reactive({
  customer_name: '',
  order_number: '',
  domain_name: '',
  nickname: '',
  product_category: 'server-rental', // 固定为主机出租分类
});

// 日期范围
const dateRange = reactive({
  order_date: [],
  expiry_date: []
});

// 表格数据
const loading = ref(false);
const rentalList = ref([]);
const selectedIds = ref([]);
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
});

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref('添加主机出租');
const dialogType = ref('add'); // add 或 edit
const viewDialogVisible = ref(false);
const detailData = ref({});

// 表单对象
const rentalFormRef = ref(null);
const rentalForm = reactive({
  id: undefined,
  customer: '',
  order_number: '',
  rental_years: 1,
  effective_date: new Date().toISOString().slice(0, 10),
  expiry_date: '',
  nickname: '',
  order_source: 0,
  order_date: new Date().toISOString().slice(0, 10),
  order_amount: '',
  order_status: 0,
  domain_name: '',
  authorization_code: '',
  order_remarks: '',
  email: '',
  mobile: '',
  customer_wechat: ''
});

// 表单验证规则
const rules = {
  customer: [{ required: true, message: '请选择客户', trigger: 'change' }],
  order_number: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
  rental_years: [{ required: true, message: '请选择出租年限', trigger: 'change' }],
  order_amount: [
    { required: true, message: '请输入订单金额', trigger: 'blur' }
  ],
  effective_date: [{ required: true, message: '请选择生效日期', trigger: 'change' }],
  expiry_date: [{ required: true, message: '请选择截至日期', trigger: 'change' }],
  domain_name: [{ required: true, message: '请输入网站域名', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的电子邮箱格式', trigger: 'blur' }]
};

// 下拉选项
const customerOptions = ref([]);
const userOptions = ref([]);
const customerLoading = ref(false);
const userLoading = ref(false);
const searchCustomerKeyword = ref('');
const searchUserKeyword = ref('');
const showCreateOption = ref(false);
const exportLoading = ref(false);

// 导入相关数据
const importDialogVisible = ref(false);
const fileList = ref([]);
const selectedFile = ref(null);
const importLoading = ref(false);

// 计算属性
const isFiltered = computed(() => {
  return Object.values(queryParams).some(value => value) || 
         dateRange.order_date.length > 0 || 
         dateRange.expiry_date.length > 0;
});

// 初始化
onMounted(async () => {
  loadUsers();
  fetchRentalList();
});

// 加载用户列表（对接人）
const loadUsers = async () => {
  try {
    const res = await getUserList();
    userOptions.value = res.data.items || [];
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败');
  }
};

// 用户远程搜索
const remoteUserSearch = async (query) => {
  searchUserKeyword.value = query;
  
  if (query) {
    userLoading.value = true;
    try {
      console.log('开始搜索用户:', query);
      const res = await getUserList({ nickname: query }); // 根据昵称搜索用户
      console.log('用户搜索返回:', res);
      
      // 解析用户数据
      let users = [];
      
      if (Array.isArray(res)) {
        users = res;
      } else if (res && typeof res === 'object') {
        if (Array.isArray(res.results)) {
          users = res.results;
        } else if (res.data) {
          if (Array.isArray(res.data)) {
            users = res.data;
          } else if (res.data.items && Array.isArray(res.data.items)) {
            users = res.data.items;
          } else if (res.data.results && Array.isArray(res.data.results)) {
            users = res.data.results;
          }
        }
      }
      
      console.log('处理后的用户数据:', users);
      
      // 确保每个用户对象有id和nickname属性，并按昵称进行过滤
      userOptions.value = users.filter(user => 
        user && user.id !== undefined && user.nickname && 
        user.nickname.toLowerCase().includes(query.toLowerCase())
      );
      
      // 如果没有匹配的结果，保留现有选项但添加提示信息
      if (userOptions.value.length === 0) {
        ElMessage.info('没有找到匹配的对接人，请尝试其他搜索关键词');
      }
      
      console.log('过滤后的用户选项:', userOptions.value);
    } catch (error) {
      console.error('搜索用户失败:', error);
      ElMessage.error('搜索用户失败，请稍后重试');
      // 搜索失败时保留现有选项
    } finally {
      userLoading.value = false;
    }
  } else {
    // 如果查询为空，则重新加载所有用户
    loadUsers();
  }
};

// 保存选择的用户或输入的对接人
const handleUserSelectChange = (value) => {
  console.log('用户选择变更:', value);
  
  // 只处理有效的用户ID
  if (value && !isNaN(Number(value))) {
    rentalForm.nickname = Number(value);
    console.log('设置对接人ID为:', rentalForm.nickname);
  }
};

// 客户远程搜索
const remoteCustomerSearch = async (query) => {
  searchCustomerKeyword.value = query;
  
  if (query) {
    customerLoading.value = true;
    try {
      console.log('开始搜索客户:', query);
      const res = await getCustomerList({ customer_name: query });
      console.log('客户搜索原始返回:', res);
      
      // 解析客户数据
      let customers = [];
      
      // 直接检查返回的结构
      if (Array.isArray(res)) {
        customers = res;
      } else if (res && typeof res === 'object') {
        if (Array.isArray(res.results)) {
          customers = res.results;
        } else if (res.data) {
          if (Array.isArray(res.data)) {
            customers = res.data;
          } else if (res.data.results && Array.isArray(res.data.results)) {
            customers = res.data.results;
          }
        }
      }
      
      console.log('处理后的客户数据:', customers);
      
      // 确保每个客户对象有id和customer_name属性
      customerOptions.value = customers.filter(customer => 
        customer && customer.id !== undefined && customer.customer_name
      );
      
      console.log('过滤后的客户选项:', customerOptions.value);
      
      // 始终显示创建新客户的选项，除非已存在相同名称
      showCreateOption.value = query.length > 0 && 
        !customerOptions.value.some(item => 
          item.customer_name.toLowerCase() === query.toLowerCase()
        );
      
      console.log('是否显示创建选项:', showCreateOption.value);
    } catch (error) {
      console.error('搜索客户失败:', error);
      customerOptions.value = [];
      // 出错时也允许创建新客户
      showCreateOption.value = query.length > 0;
    } finally {
      customerLoading.value = false;
    }
  } else {
    // 清空查询时不显示任何选项
    customerOptions.value = [];
    showCreateOption.value = false;
  }
};

// 客户选择变更
const handleCustomerSelectChange = async (value) => {
  console.log('客户选择变更:', value);
  if (value === 'create_new') {
    try {
      console.log('创建新客户:', searchCustomerKeyword.value);
      
      // 确保客户名称不为空
      if (!searchCustomerKeyword.value || searchCustomerKeyword.value.trim() === '') {
        ElMessage.warning('客户名称不能为空');
        rentalForm.customer = '';
        return;
      }
      
      // 准备创建客户数据
      const createData = { 
        customer_name: searchCustomerKeyword.value,
        customer_source: rentalForm.order_source 
      };
      console.log('创建客户数据:', createData);
      
      // 调用API创建客户
      const res = await createCustomer(createData);
      console.log('创建客户返回:', res);
      
      // 处理返回数据
      let newCustomer = null;
      let newCustomerId = null;
      
      if (res && typeof res === 'object') {
        if (res.data) {
          newCustomer = res.data;
          newCustomerId = newCustomer.id;
        } else if (res.id && res.customer_name) {
          newCustomer = res;
          newCustomerId = res.id;
        }
      }
      
      if (!newCustomer || !newCustomerId) {
        throw new Error('创建客户成功但返回数据不完整');
      }
      
      ElMessage.success('创建客户成功');
      
      console.log('新创建的客户:', newCustomer, '客户ID:', newCustomerId);
      
      // 将新客户添加到选项中
      customerOptions.value = [newCustomer, ...customerOptions.value];
      
      // 设置表单的客户ID - 确保是数字类型
      rentalForm.customer = Number(newCustomerId);
      
      // 关闭创建选项
      showCreateOption.value = false;
    } catch (error) {
      console.error('创建客户失败:', error);
      ElMessage.error('创建客户失败: ' + (error.message || '未知错误'));
      rentalForm.customer = '';
    }
  } else if (value) {
    // 确保选择的客户ID是数字类型
    rentalForm.customer = Number(value);
    console.log('设置客户ID为:', rentalForm.customer);
  }
};

// 获取订单来源名称的辅助函数
const getOrderSourceName = (sourceCode) => {
  const sources = {
    0: 'Newbe工作室',
    1: '纽币德信息科技',
    2: '官方网站',
    3: '其它'
  };
  return sources[sourceCode] || '未知来源';
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  
  try {
    // 处理ISO日期格式
    if (dateString.includes('T')) {
      const date = new Date(dateString);
      
      // 判断是否为有效日期
      if (isNaN(date.getTime())) {
        return dateString;
      }
      
      // 格式化为 YYYY-MM-DD HH:MM:SS
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    }
    
    // 如果已经是简单的日期格式，则直接返回
    return dateString;
  } catch (error) {
    console.error('日期格式化错误:', error);
    return dateString;
  }
};

// 获取主机出租列表
const fetchRentalList = async () => {
  loading.value = true;
  try {
    // 处理日期范围
    const params = { ...queryParams };
    if (dateRange.order_date && dateRange.order_date.length === 2) {
      params.order_date_start = dateRange.order_date[0];
      params.order_date_end = dateRange.order_date[1];
    }
    if (dateRange.expiry_date && dateRange.expiry_date.length === 2) {
      params.expiry_date_start = dateRange.expiry_date[0];
      params.expiry_date_end = dateRange.expiry_date[1];
    }
    
    // 添加分页
    params.page = pagination.page;
    params.page_size = pagination.pageSize;
    
    const res = await getRentalList(params);
    console.log('主机出租列表API返回:', res);
    
    // 处理返回结果
    if (res.data && res.data.results) {
      rentalList.value = res.data.results;
      pagination.total = res.data.count || 0;
    } else if (res.results) {
      rentalList.value = res.results;
      pagination.total = res.count || 0;
    } else if (res.data && Array.isArray(res.data)) {
      rentalList.value = res.data;
      pagination.total = res.data.length;
    } else if (Array.isArray(res)) {
      rentalList.value = res;
      pagination.total = res.length;
    } else {
      rentalList.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error('获取主机出租列表失败:', error);
    ElMessage.error('获取主机出租列表失败');
    rentalList.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 查询按钮
const handleQuery = () => {
  pagination.page = 1;
  fetchRentalList();
};

// 重置查询
const resetQuery = () => {
  Object.keys(queryParams).forEach(key => {
    if (key !== 'product_category') {
      queryParams[key] = '';
    }
  });
  dateRange.order_date = [];
  dateRange.expiry_date = [];
  pagination.page = 1;
  fetchRentalList();
};

// 表格选择项变更
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id);
};

// 分页大小变更
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  fetchRentalList();
};

// 当前页变更
const handleCurrentChange = (val) => {
  pagination.page = val;
  fetchRentalList();
};

// 添加主机出租
const handleAdd = () => {
  dialogTitle.value = '添加主机出租';
  dialogType.value = 'add';
  resetForm();
  dialogVisible.value = true;
};

// 编辑主机出租
const handleEdit = async (row) => {
  dialogTitle.value = '编辑主机出租';
  dialogType.value = 'edit';
  resetForm();
  
  try {
    loading.value = true;
    const res = await getRental(row.id);
    
    // 处理API响应数据
    const data = res.data || res;
    
    // 先复制基本字段
    Object.keys(rentalForm).forEach(key => {
      if (data[key] !== undefined) {
        rentalForm[key] = data[key];
      }
    });
    
    // 确保客户ID是数字类型
    if (data.customer && typeof data.customer === 'object' && data.customer.id) {
      rentalForm.customer = Number(data.customer.id);
      
      // 确保客户选项中包含此客户
      const existingCustomer = customerOptions.value.find(c => c.id === data.customer.id);
      if (!existingCustomer && data.customer.customer_name) {
        customerOptions.value.push({
          id: data.customer.id,
          customer_name: data.customer.customer_name
        });
      }
    } else if (data.customer) {
      rentalForm.customer = Number(data.customer);
    }
    
    // 确保金额是字符串类型，便于输入
    if (data.order_amount !== undefined) {
      rentalForm.order_amount = String(data.order_amount);
    }
    
    dialogVisible.value = true;
  } catch (error) {
    console.error('获取主机出租详情失败:', error);
    ElMessage.error('获取主机出租详情失败');
  } finally {
    loading.value = false;
  }
};

// 查看主机出租详情
const handleView = async (row) => {
  try {
    loading.value = true;
    console.log('查看主机出租详情, ID:', row.id);
    
    const res = await getRental(row.id);
    console.log('获取到的主机出租详情数据:', res);
    
    // 确保详情数据正确处理
    if (res.data) {
      detailData.value = res.data;
    } else if (typeof res === 'object') {
      detailData.value = res;
    } else {
      throw new Error('获取详情数据格式不正确');
    }
    
    console.log('处理后的详情数据:', detailData.value);
    viewDialogVisible.value = true;
  } catch (error) {
    console.error('获取主机出租详情失败:', error);
    ElMessage.error('获取主机出租详情失败: ' + (error.message || '未知错误'));
  } finally {
    loading.value = false;
  }
};

// 删除主机出租
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除订单 ${row.order_number} 吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true;
      await deleteRental(row.id);
      ElMessage.success('删除成功');
      fetchRentalList();
    } catch (error) {
      console.error('删除主机出租失败:', error);
      ElMessage.error('删除主机出租失败');
    } finally {
      loading.value = false;
    }
  }).catch(() => {});
};

// 批量删除主机出租
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录');
    return;
  }
  
  ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 条记录吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true;
      await batchDeleteRentals(selectedIds.value);
      ElMessage.success('批量删除成功');
      fetchRentalList();
    } catch (error) {
      console.error('批量删除主机出租失败:', error);
      ElMessage.error('批量删除主机出租失败');
    } finally {
      loading.value = false;
    }
  }).catch(() => {});
};

// 导出主机出租数据
const handleExport = async () => {
  try {
    exportLoading.value = true;
    // 处理日期范围
    const params = { ...queryParams };
    if (dateRange.order_date && dateRange.order_date.length === 2) {
      params.order_date_start = dateRange.order_date[0];
      params.order_date_end = dateRange.order_date[1];
    }
    if (dateRange.expiry_date && dateRange.expiry_date.length === 2) {
      params.expiry_date_start = dateRange.expiry_date[0];
      params.expiry_date_end = dateRange.expiry_date[1];
    }
    
    const response = await exportRentals(params);
    
    // 检查响应类型
    if (!(response instanceof Blob)) {
      console.error('导出返回的不是Blob数据:', response);
      ElMessage.error('导出失败: 服务器返回格式错误');
      return;
    }
    
    // 验证Blob内容是否有效
    if (response.size === 0) {
      ElMessage.error('导出失败: 返回的文件内容为空');
      return;
    }
    
    // 创建下载链接
    const link = document.createElement('a');
    link.href = URL.createObjectURL(response);
    link.download = `主机出租数据_${new Date().getTime()}.xlsx`;
    document.body.appendChild(link);
    link.click();
    
    // 延迟移除链接，确保下载开始
    setTimeout(() => {
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href);
    }, 100);
    
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出主机出租数据失败:', error);
    ElMessage.error('导出主机出租数据失败: ' + (error.message || '未知错误'));
  } finally {
    exportLoading.value = false;
  }
};

// 打开导入对话框
const handleImport = () => {
  importDialogVisible.value = true;
  fileList.value = [];
  selectedFile.value = null;
};

// 处理文件变更
const handleFileChange = (file) => {
  fileList.value = [file];
  selectedFile.value = file.raw;
  console.log('已选择文件:', file.name);
};

// 提交导入
const submitImport = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请选择要导入的Excel文件');
    return;
  }
  
  importLoading.value = true;
  
  try {
    const formData = new FormData();
    formData.append('file', selectedFile.value);
    
    const res = await importRentals(formData);
    
    ElMessage.success(`导入成功，已导入 ${res.imported_count || res.success_count || '多条'} 条数据`);
    importDialogVisible.value = false;
    
    // 刷新列表
    fetchRentalList();
  } catch (error) {
    console.error('导入失败:', error);
    const errorMsg = error.response?.data?.message || error.message || '导入失败';
    ElMessage.error(errorMsg);
  } finally {
    importLoading.value = false;
  }
};

// 下载导入模板
const downloadTemplate = async () => {
  try {
    ElMessage.info('正在准备下载模板...');
    // 调用API函数获取模板
    const response = await getHostOrderImportTemplate();
    
    // 检查响应类型
    if (!(response instanceof Blob)) {
      console.error('下载模板返回的不是Blob数据:', response);
      ElMessage.error('下载模板失败: 服务器返回格式错误');
      return;
    }
    
    // 验证Blob内容是否有效
    if (response.size === 0) {
      ElMessage.error('下载模板失败: 返回的文件内容为空');
      return;
    }
    
    // 创建下载链接
    const link = document.createElement('a');
    link.href = URL.createObjectURL(response);
    link.download = '主机出租数据导入模板.xlsx';
    document.body.appendChild(link);
    link.click();
    
    // 延迟移除链接，确保下载开始
    setTimeout(() => {
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href);
    }, 100);
    
    ElMessage.success('导入模板下载成功');
  } catch (error) {
    console.error('下载模板失败:', error);
    ElMessage.error('下载模板失败: ' + (error.message || '请稍后重试'));
  }
};

// 提交表单
const submitForm = async () => {
  if (!rentalFormRef.value) return;
  
  await rentalFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true;
        
        // 准备表单数据
        const formData = { ...rentalForm };
        
        // 确保客户ID是数字类型
        if (formData.customer && typeof formData.customer !== 'number') {
          formData.customer = parseInt(formData.customer, 10);
          console.log('转换后的客户ID:', formData.customer);
        }
        
        // 确保对接人ID是数字类型或null
        if (formData.nickname !== null && formData.nickname !== undefined && typeof formData.nickname !== 'number') {
          if (!isNaN(Number(formData.nickname))) {
            formData.nickname = Number(formData.nickname);
            console.log('转换后的对接人ID:', formData.nickname);
          } else {
            // 如果不能转为有效ID，置为null
            formData.nickname = null;
          }
        }
        
        // 确保金额是数字类型
        if (formData.order_amount !== undefined && formData.order_amount !== null) {
          formData.order_amount = parseFloat(formData.order_amount);
          if (isNaN(formData.order_amount)) {
            ElMessage.error('订单金额必须是有效的数字');
            return;
          }
        }
        
        console.log('提交的表单数据:', formData);
        
        if (dialogType.value === 'add') {
          await createRental(formData);
          ElMessage.success('添加成功');
        } else {
          await updateRental(formData.id, formData);
          ElMessage.success('更新成功');
        }
        
        dialogVisible.value = false;
        fetchRentalList();
      } catch (error) {
        console.error('保存主机出租数据失败:', error);
        ElMessage.error('保存失败: ' + (error.response?.data?.detail || error.message || '未知错误'));
      } finally {
        loading.value = false;
      }
    }
  });
};

// 重置表单
const resetForm = () => {
  if (rentalFormRef.value) {
    rentalFormRef.value.resetFields();
  }
  
  Object.keys(rentalForm).forEach(key => {
    switch (key) {
      case 'order_source':
        rentalForm[key] = 0;
        break;
      case 'rental_years':
        rentalForm[key] = 1;
        break;
      case 'order_status':
        rentalForm[key] = 0;
        break;
      case 'order_date':
        rentalForm[key] = new Date().toISOString().slice(0, 10);
        break;
      default:
        rentalForm[key] = '';
        break;
    }
  });
  
  rentalForm.id = undefined;
};
</script>

<style scoped>
.apple-style-container {
  padding: 0 10px 10px 10px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
  background-color: #f5f5f7;
  min-height: calc(100vh - 100px);
  max-width: 98%;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0;
}

.filter-card, .table-card {
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  margin-bottom: 24px;
  background-color: white;
}

.filter-card {
  padding: 16px;
}

.table-card {
  padding: 16px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.left-buttons, .right-buttons {
  display: flex;
  gap: 8px;
}

.apple-button {
  border-radius: 20px;
  height: 40px;
  padding: 0 16px;
  font-size: 14px;
  font-weight: 500;
  border: none;
  background: rgba(0, 0, 0, 0.05);
  color: #1d1d1f;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.apple-button:hover {
  background: rgba(0, 0, 0, 0.1);
}

.primary-button {
  background: #0071e3;
  color: white;
}

.primary-button:hover {
  background: #0077ed;
  opacity: 0.9;
}

.danger-button {
  background: #ff3b30;
  color: white;
}

.danger-button:hover {
  background: #ff4f45;
  opacity: 0.9;
}

.success-button {
  background: #34c759;
  color: white;
}

.success-button:hover {
  background: #30d158;
  opacity: 0.9;
}

.apple-table {
  border-radius: 12px;
  overflow: hidden;
}

.apple-link-button {
  font-size: 14px;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

:deep(.apple-input .el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #d2d2d7;
  transition: box-shadow 0.3s ease;
}

:deep(.apple-input .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #86868b;
}

:deep(.apple-input .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px #0071e3;
}

:deep(.apple-select .el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #d2d2d7;
}

:deep(.apple-select .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #86868b;
}

:deep(.apple-select .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px #0071e3;
}

:deep(.apple-date-picker .el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #d2d2d7;
}

:deep(.apple-date-picker .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #86868b;
}

:deep(.apple-date-picker .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px #0071e3;
}

:deep(.el-table th.el-table__cell) {
  background-color: #f5f7fa;
  font-weight: 600;
  color: #333;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #0071e3;
}

:deep(.apple-dialog .el-dialog__header) {
  padding: 16px 20px;
  margin: 0;
  background: #f5f7fa;
  border-bottom: 1px solid #e6e6e6;
}

:deep(.apple-dialog .el-dialog__footer) {
  padding: 16px 20px;
  margin: 0;
  border-top: 1px solid #e6e6e6;
}

:deep(.apple-dialog .el-dialog__body) {
  padding: 20px;
}

:deep(.apple-descriptions .el-descriptions__label) {
  background-color: #f8f8fc;
}

.apple-textarea {
  width: 100%;
}

:deep(.apple-textarea .el-textarea__inner) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #d2d2d7;
  transition: box-shadow 0.3s ease;
}

:deep(.apple-textarea .el-textarea__inner:hover) {
  box-shadow: 0 0 0 1px #86868b;
}

:deep(.apple-textarea .el-textarea__inner:focus) {
  box-shadow: 0 0 0 2px #0071e3;
}

.apple-tag {
  border-radius: 10px;
  padding: 2px 10px;
}

:deep(.apple-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

/* 详情弹窗样式更新 */
:deep(.rental-detail-dialog .el-dialog__header) {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  margin-right: 0;
}

:deep(.rental-detail-dialog .el-dialog__body) {
  padding: 0;
  max-height: 65vh;
  overflow-y: auto;
}

.rental-detail-container {
  padding: 0;
}

.detail-header {
  background-color: #f5f7fa;
  padding: 16px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-content {
  padding: 20px 24px;
}

/* 水平列布局 */
.detail-columns {
  display: flex;
  gap: 40px;
  margin-bottom: 24px;
}

.detail-column {
  flex: 1;
  min-width: 0; /* 防止内容溢出 */
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section.full-width {
  width: 100%;
}

.detail-section:last-child {
  margin-bottom: 0;
}

.section-title {
  font-size: 15px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0 0 12px 0;
  padding-bottom: 6px;
  border-bottom: 1px solid #f0f0f0;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.detail-item {
  display: flex;
  flex-direction: column;
}

.item-label {
  font-size: 12px;
  color: #86868b;
  margin-bottom: 4px;
}

.item-value {
  font-size: 14px;
  color: #1d1d1f;
  font-weight: 500;
}

.remarks-box {
  background-color: #f5f7fa;
  border-radius: 8px;
  padding: 12px 16px;
  min-height: 60px;
  max-height: 100px;
  overflow-y: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.edit-button {
  background-color: #0071e3;
  color: white;
  border: none;
}

.edit-button:hover {
  background-color: #0062c3;
}

.empty-data {
  padding: 40px;
  text-align: center;
}

/* 导入弹窗样式 */
.import-dialog-content {
  padding: 20px 0;
}

.import-tip {
  margin-bottom: 15px;
  font-size: 14px;
  color: #606266;
}

.download-template-btn {
  color: #0071e3;
  padding-left: 0;
}

.download-template-btn:hover {
  color: #1890ff;
}

/* 上传组件样式 */
:deep(.el-upload-dragger) {
  width: 100%;
  height: 150px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

:deep(.el-upload__tip) {
  line-height: 1.5;
  margin-top: 10px;
  color: #606266;
}

:deep(.el-upload-list) {
  margin-top: 15px;
}
</style> 